<template>
  <el-card class="box-card">
    <el-form ref="form" :rules="rules" :model="ruleForm">
      <el-form-item
        style="width:25%;display:inline-block;margin-right:15px"
        label-width="80px"
        label="属性名"
        prop="attrName"
        :rules="[{ required: true, message: '请输入属性名', trigger: 'blur' }]"
      >
        <el-input v-model="ruleForm.attrName" placeholder="请输入属性名" />
      </el-form-item>
      <el-button
        type="primary"
        :disabled="!ruleForm.attrName"
        icon="el-icon-plus"
        @click="addEmptyAttrValue"
      >添加属性</el-button>
      <el-form-item prop="attrValueList">
        <el-table :data="ruleForm.attrValueList" border class="table">
          <el-table-column type="index" label="序号" width="50" align="center" />
          <el-table-column label="属性名">
            <template v-slot="{ row, $index }">
              <el-input
                v-if="row.isShowEidt"
                :ref="$index"
                v-model="row.valueName"
                size="mini"
                @blur="handleInputBlur(row, $index)"
              />
              <div v-else @click="showEdit(row, $index)">
                {{ row.valueName }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot="{ row, $index }">
              <el-popconfirm
                confirm-button-text="确定"
                cancel-button-text="取消"
                icon="el-icon-info"
                icon-color="red"
                :title="`确定要删除 ${row.valueName} 属性值吗？`"
                @onConfirm="ruleForm.attrValueList.splice($index, 1)"
              >
                <el-button
                  slot="reference"
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                />
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <el-button type="primary" @click="addNewAttrs">确认</el-button>
    <el-button @click="$emit('setIsShowAttrList', true)">取消</el-button>
  </el-card>
</template>

<script>
import { mapState } from 'vuex'
import { reqSaveAttr } from '@/api/product/attr'
export default {
  name: 'SaveAttr',
  props: {
    currentAttr: {
      type: Object,
      default: () => ({
        // 属性名
        attrName: '',
        // 属性值列表
        attrValueList: []
      })
    }
  },
  data() {
    function validator(rule, value, callback) {
      if (value.length) {
        callback()
        return
      }
      callback('请至少添加一个属性值')
    }

    return {
      ruleForm: this.currentAttr,
      rules: {
        attrValueList: [{ required: true, validator }]
      }
    }
  },
  computed: {
    ...mapState('category', ['category3Id'])
  },
  methods: {
    // 添加一个属性
    addEmptyAttrValue() {
      this.ruleForm.attrValueList.push({ valueName: '', isShowEidt: true })
      this.$nextTick(() => {
        this.$refs[this.ruleForm.attrValueList.length - 1].focus()
      })
    },
    // 点击显示输入框
    showEdit(row, index) {
      // 更新属性时，数据一上来没有isEdit属性，他不是响应式数据,所以要改成响应式的
      this.$set(row, 'isShowEidt', true)
      this.$nextTick(() => {
        this.$refs[index].focus()
      })
    },
    // 输入框失去焦点事件
    handleInputBlur(row, index) {
      // 输入为空就删除
      if (!row.valueName) {
        this.ruleForm.attrValueList.splice(index, 1)
        return
      }
      row.isShowEidt = false
    },
    // 确认添加新属性
    addNewAttrs() {
      // 验证属性名和属性值是否都有
      const { category3Id } = this
      this.$refs.form.validate(async valid => {
        if (valid) {
          const { attrName, attrValueList } = this.ruleForm
          await reqSaveAttr({
            attrName,
            attrValueList: attrValueList.map(attrValue => {
              return {
                valueName: attrValue.valueName
              }
            }),
            categoryId: category3Id,
            categoryLevel: 3
          })
          this.$message({
            type: 'success',
            message: '添加属性成功~'
          })
          this.$emit('setIsShowAttrList', true)
        }
      })
    }
  }
}
</script>

<style lang="sass" scoped>
.table
  margin:15px
</style>
